# -*- coding: utf-8 -*-
"""
Created on Tue Apr  9 15:28:11 2020

@author: Bairong
"""

import numpy as np
import pandas as pd
# from time import strptime
# from datetime import datetime
# from operator import itemgetter
from abstractApi import AbstractModel

import re


class FeatureDerive(AbstractModel):  # Like FeatureModel  
# class FeatureDerive():
    
    
    def __init__(self):
        return 
        
    def loadParam(self, fileParam):
        pass
        
    def _derive(self, data, inparam):
        """
        data: dict<str, T>
        inparam: dict<str, T>
        rtype: dict<str, T>
        """
        result = {}
      
        # load three key elements: name, id and cell number 
#        exdata = param["inparam"]

        # 添加客群参数
        # param["inparam"]["cus_group"] = "credit"
        # param["inparam"]["cus_group"] = "cashon"
       
        # 借贷意向验证衍生特征 alf_time_intedays_d30_mean alf_apirisk_time_lenth_d90_sum
        result['flag_ApplyFeature'] = '0'
        if 'flag_ApplyFeature' in data and data['flag_ApplyFeature'] != '':
            result['flag_ApplyFeature'] = data['flag_ApplyFeature']

        result['alf_time_intedays_d30_mean'] = ''
        result['alf_apirisk_time_lenth_d90_sum'] = ''
        if result['flag_ApplyFeature'] == '1':
            if 'alf_time_intedays_d30_mean' in data:
                result['alf_time_intedays_d30_mean'] = data['alf_time_intedays_d30_mean']
            if 'alf_apirisk_time_lenth_d90_sum' in data:
                result['alf_apirisk_time_lenth_d90_sum'] = data['alf_apirisk_time_lenth_d90_sum']

        
        ### 借贷意向验证 als_d15_id_nbank_oth_orgnum als_m6_id_nbank_cf_orgnum
        result['flag_applyloanstr'] = '0'
        if 'flag_applyloanstr' in data and data['flag_applyloanstr'] != '':
            result['flag_applyloanstr'] = data['flag_applyloanstr']

        result['als_d15_id_nbank_oth_orgnum'] = ''
        result['als_m6_id_nbank_cf_orgnum'] = ''
        if result['flag_applyloanstr'] == '1':
            if 'als_d15_id_nbank_oth_orgnum' in data:
                result['als_d15_id_nbank_oth_orgnum'] = data['als_d15_id_nbank_oth_orgnum']
            if 'als_m6_id_nbank_cf_orgnum' in data:
                result['als_m6_id_nbank_cf_orgnum'] = data['als_m6_id_nbank_cf_orgnum']

        ### 借贷申请分位数 ql_d15_id_nbank_top_orgnum
        result['flag_quantilelevel'] = '0'
        if 'flag_quantilelevel' in data and data['flag_quantilelevel'] != '':
            result['flag_quantilelevel'] = data['flag_quantilelevel']

        result['ql_d15_id_nbank_top_orgnum'] = ''
        if result['flag_quantilelevel'] == '1':
            if 'ql_d15_id_nbank_top_orgnum' in data:
                result['ql_d15_id_nbank_top_orgnum'] = data['ql_d15_id_nbank_top_orgnum']
        
        ### 入模产品A mma_var236
        result['flag_multiplemodela'] = '0'
        if 'flag_multiplemodela' in data and data['flag_multiplemodela'] != '':
            result['flag_multiplemodela'] = data['flag_multiplemodela']

        result['mma_var236'] = ''
        if result['flag_multiplemodela'] == '1':
            if 'mma_var236' in data:
                result['mma_var236'] = data['mma_var236']
        
        ### 借贷行为验证 tl_cell_t10_nbank_reamt
        result['flag_totalloan'] = '0'
        if 'flag_totalloan' in data and data['flag_totalloan'] != '':
            result['flag_totalloan'] = data['flag_totalloan']

        result['tl_cell_t10_nbank_reamt'] = ''
        if result['flag_totalloan'] == '1':
            if 'tl_cell_t10_nbank_reamt' in data:
                result['tl_cell_t10_nbank_reamt'] = data['tl_cell_t10_nbank_reamt']
        
        ### 人口衍生 pd_cell_city_rent_sort
        result['flag_populationderivation'] = '0'
        if 'flag_populationderivation' in data and data['flag_populationderivation'] != '':
            result['flag_populationderivation'] = data['flag_populationderivation']

        result['pd_cell_city_rent_sort'] = ''
        if result['flag_populationderivation'] == '1':
            if 'pd_cell_city_rent_sort' in data:
                result['pd_cell_city_rent_sort'] = data['pd_cell_city_rent_sort']

        for key in result.keys():
            result[key] = str(result[key])
        result = dict(zip(result.keys(), [str(result[key]) for key in result]))
        # features_pd = pd.Series(result)
        return result


    def _predict(self,data):
     
        '''''@sig public Map<String,String> start(Map<String,String> data)'''
        
        """
        入口函数
        规则或者模型计算
        参数:
        data: {类型: dict,key:string value:string} derive输出
        返回值:
            {类型:dict,key:string value:string} 返回给用户结果　
        notice:
            不要使用全局变量
        """
        # data = self._derive(data)
        result = {}
        # als_d15_id_nbank_oth_orgnum
        if data['als_d15_id_nbank_oth_orgnum'] == '':
            data['als_d15_id_nbank_oth_orgnum_b'] = 13  
        elif float(data['als_d15_id_nbank_oth_orgnum']) < 1.5:
            data['als_d15_id_nbank_oth_orgnum_b'] = -12                            
        else:
            data['als_d15_id_nbank_oth_orgnum_b'] = -56

    
        # ql_d15_id_nbank_top_orgnum
        if data['ql_d15_id_nbank_top_orgnum'] == '':
            data['ql_d15_id_nbank_top_orgnum_b'] = 19  
        elif float(data['ql_d15_id_nbank_top_orgnum']) < 0.93:
            data['ql_d15_id_nbank_top_orgnum_b'] = 43               
        elif float(data['ql_d15_id_nbank_top_orgnum']) < 0.937:
            data['ql_d15_id_nbank_top_orgnum_b'] = -45                
        else:
            data['ql_d15_id_nbank_top_orgnum_b'] = -65
  
        # mma_var236
        if data['mma_var236'] == '':
            data['mma_var236_b'] = -13  
        elif float(data['mma_var236']) < 78.5:
            data['mma_var236_b'] = 40                           
        else:
            data['mma_var236_b'] = 222
                
            
        # alf_time_intedays_d30_mean
        if data['alf_time_intedays_d30_mean'] == '':
            data['alf_time_intedays_d30_mean_b'] = 19  
        elif float(data['alf_time_intedays_d30_mean']) < 1.845:
            data['alf_time_intedays_d30_mean_b'] = -38               
        elif float(data['alf_time_intedays_d30_mean']) < 2.817:
            data['alf_time_intedays_d30_mean_b'] = -11               
        else:
            data['alf_time_intedays_d30_mean_b'] = 9  
            
        # als_m6_id_nbank_cf_orgnum
        if data['als_m6_id_nbank_cf_orgnum'] == '':
            data['als_m6_id_nbank_cf_orgnum_b'] = -4
        elif float(data['als_m6_id_nbank_cf_orgnum']) < 5.5:
            data['als_m6_id_nbank_cf_orgnum_b'] = 8
        else:
            data['als_m6_id_nbank_cf_orgnum_b'] = -65  
            
        # alf_apirisk_time_lenth_d90_sum
        if data['alf_apirisk_time_lenth_d90_sum'] == '':
            data['alf_apirisk_time_lenth_d90_sum_b'] = -29  
        elif float(data['alf_apirisk_time_lenth_d90_sum']) < 10.663:
            data['alf_apirisk_time_lenth_d90_sum_b'] = 58               
        elif float(data['alf_apirisk_time_lenth_d90_sum']) < 53.01:
            data['alf_apirisk_time_lenth_d90_sum_b'] = 1               
        else:
            data['alf_apirisk_time_lenth_d90_sum_b'] = -33  
                
        # tl_cell_t10_nbank_reamt
        if data['tl_cell_t10_nbank_reamt'] == '':
            data['tl_cell_t10_nbank_reamt_b'] = -31  
        elif float(data['tl_cell_t10_nbank_reamt']) < 29.5:
            data['tl_cell_t10_nbank_reamt_b'] = 23                         
        else:
            data['tl_cell_t10_nbank_reamt_b'] = -65
            
        # pd_cell_city_rent_sort
        if data['pd_cell_city_rent_sort'] == '':
            data['pd_cell_city_rent_sort_b'] = 0  
        elif float(data['pd_cell_city_rent_sort']) < 95.5:
            data['pd_cell_city_rent_sort_b'] = 51               
        elif float(data['pd_cell_city_rent_sort']) < 325.5:
            data['pd_cell_city_rent_sort_b'] = 0              
        else:
            data['pd_cell_city_rent_sort_b'] = -32  
                
        #######all
        
        score = data['als_d15_id_nbank_oth_orgnum_b']+data['ql_d15_id_nbank_top_orgnum_b']+data['mma_var236_b']+data['alf_time_intedays_d30_mean_b']+data['als_m6_id_nbank_cf_orgnum_b']+data['alf_apirisk_time_lenth_d90_sum_b']+data['tl_cell_t10_nbank_reamt_b']+data['pd_cell_city_rent_sort_b']
        
        score_ = 597 #基础分数由A+B*w0计算 其中，w0是截距项，A和B由score = A + B*ln(odds)根据score0和PDO计算
        data['point'] = str(score_ + score)
        result['point'] = data['point']  
        
        return {'lr_prob': result['point']}
 

    def _if_return(self, data):
        fr = re.compile(r'^flag_')
        flag_list = [i for i in data if fr.search(i)]
        data_temp = {key:values for key,values in data.items() if key in flag_list}

        if_return_value = 0
        for i in flag_list:
            try:
                if float(data_temp.get(i,0)) == 0 or float(data_temp.get(i,0)) == 1:
                    data_temp[i] = data_temp[i]
                else:
                    data_temp[i] = 0
            except:
                data_temp[i] = 0
            if_return_value += float(data_temp.get(i,0))
        
        return if_return_value
          
    def predict(self, data):
        """
        param: dict<str, T>
        rtype: dict<str, T>
        """
        # param={"brData":{"als_m12_id_nbank_avg_monnum": "1.25", "als_fst_id_nbank_inteday": "329", "als_m3_id_nbank_night_orgnum": "2", "als_m6_id_rel_orgnum": "",
        #                  "ald_id_nbank_orgnum": "", "flag_applyloanstr": "0", "flag_applyloan_d": "1"},"extraData":{"cus_num": "31543"},"inparam":{"cus_num": "31543"},"strategyType":"","pointType":"scoreconson","scoreData":"2","scoreBaseMealId":"","swiftNumber":"","scoreType":{"score":"scoreconson","api":"S7_0"},"apiCode":"4002497"}
        # param = {"brData":{"flag_applyloanstr": "1", "flag_graylistexpand": "0", "flag_multiplemodela": "1", "flag_populationderivation": "1", "gl_m1_beyond6_hit_months": "0", "gl_m1_max_list_level": "1", "pd_id_city_old_house_sort": ""},"extraData":{"cus_num": "10568"},"inparam":{"cus_num": "10568", "score": "774"},"strategyType":"","pointType":"scoremixbj","scoreData":"2","scoreBaseMealId":"","swiftNumber":"","scoreType":[{"score":"scoremixbj","api":"S1_0"}],"apiCode":"4002497"}

        # data = param['brData']
        # inparam = param['inparam']

        res = {}
        res['point']=''

        # param["outLevel"] = '2'
        p = param.get('outLevel','')

        if_return_value = self._if_return(data)


        if if_return_value != 0:
            features_pd  = self._derive(data,inparam)
            prob = self._predict(features_pd)
            res['point'] = prob['lr_prob']
            if p == 2:
                res['score_derive'] = {
                        'alf_time_intedays_d30_mean': features_pd['alf_time_intedays_d30_mean'],
                        'alf_apirisk_time_lenth_d90_sum': features_pd['alf_apirisk_time_lenth_d90_sum'],
                        'als_d15_id_nbank_oth_orgnum': features_pd['als_d15_id_nbank_oth_orgnum'],
                        'als_m6_id_nbank_cf_orgnum': features_pd['als_m6_id_nbank_cf_orgnum'],
                        'mma_var236': features_pd['mma_var236'],
                        'pd_cell_city_rent_sort': features_pd['pd_cell_city_rent_sort'],
                        'ql_d15_id_nbank_top_orgnum': features_pd['ql_d15_id_nbank_top_orgnum'],
                        'tl_cell_t10_nbank_reamt': features_pd['tl_cell_t10_nbank_reamt']}
        else:
            res['point'] = ''
    
        if res['point'] != '' and float(res['point']) < 300:
            res['point'] = '300'
        elif res['point'] != '' and float(res['point']) > 1000:
            res['point'] = '1000'    

        return res
        
####线下验证
import os
os.chdir(r"D:\模型上线\1.验证")
os.listdir()
fd = FeatureDerive()
df1 = pd.read_csv('testest_3000_postmant_001.csv', dtype=str , sep = ",",skiprows = [1])
df1 = df1.fillna('')
df = df1.to_dict('records')
#转为单条字典格式
result = []
for i in range(len(df)):
    data = df[i]
#        print(i)
    score = fd.predict(data)['point']
    # sd = fd.predict(data)['score_derive'] #衍生变量
    if score != '':
        flag_score = 1
    else:
        flag_score = 0

    # der = fd._derive(data)

    tmp = [data['cus_num'],
           data['als_d15_id_nbank_oth_orgnum'],
           data['ql_d15_id_nbank_top_orgnum'],
           data['mma_var236'],
           data['alf_time_intedays_d30_mean'],
           data['als_m6_id_nbank_cf_orgnum'],
           data['alf_apirisk_time_lenth_d90_sum'],
           data['tl_cell_t10_nbank_reamt'],
           data['pd_cell_city_rent_sort'],
           flag_score,score]

    # tmp = [data['cus_num'],
    #        sd['als_d15_id_nbank_oth_orgnum'],
    #        sd['ql_d15_id_nbank_top_orgnum'],
    #        sd['mma_var236'],
    #        sd['alf_time_intedays_d30_mean'],
    #        sd['als_m6_id_nbank_cf_orgnum'],
    #        sd['alf_apirisk_time_lenth_d90_sum'],
    #        sd['tl_cell_t10_nbank_reamt'],
    #        sd['pd_cell_city_rent_sort'],
    #        flag_score,score]
           
    result.append(tmp)
    header = ['cus_num',
          'als_d15_id_nbank_oth_orgnum',
          'ql_d15_id_nbank_top_orgnum',
          'mma_var236',
          'alf_time_intedays_d30_mean',
          'als_m6_id_nbank_cf_orgnum',
          'alf_apirisk_time_lenth_d90_sum',
          'tl_cell_t10_nbank_reamt',
          'pd_cell_city_rent_sort',
          'flag_score','score']

result = pd.DataFrame(result, dtype='str', columns=header)
result.to_csv('打分结果.csv',index=False, encoding='utf-8')


